﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using ProcurementManagement.Applcation.Command.ProcurementReturnCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.ProcurementReturnCommandHandler
{
    public class AddProcurementReturnCommandHandler : IRequestHandler<AddProcurementReturnCommand, int>
    {
        IPurchaseReturnsRepository prRep;
        IReturnProductRepository rpRep;
        IMapper mapper;
        ISqlSugarClient db;

        public AddProcurementReturnCommandHandler(IPurchaseReturnsRepository prRep,
        IMapper mapper, ISqlSugarClient db, IReturnProductRepository rpRep)
        {
            this.prRep = prRep;
            this.mapper = mapper;
            this.db = db;
            this.rpRep = rpRep;
        }

        public async Task<int> Handle(AddProcurementReturnCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //添加采购退货
                var procurement1 = mapper.Map<PurchaseReturns>(request.AddDto);
                procurement1.PurchaseReturnsCode = Guid.NewGuid().ToString();
                procurement1.RefundAmoun = 0;
                var taskToAdd = await prRep.AddAsync(procurement1);


                //添加采购退货产品
                foreach (var item in request.AddDto.returnProductLists)
                {
                    ReturnProduct detail = new ReturnProduct
                    {
                        ProductId=item.ProductId,
                        PurchaseReturnsCode = procurement1.PurchaseReturnsCode,
                        RPNum=item.RPNum,
                        RPPrice=item.RPPrice,
                        Office_Id = item.Office_Id,
                        User_Id = item.User_Id
                    };
                    await rpRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
